<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\BaseController;
use App\Entity\UserEntity;
use App\Http\Requests\Api\ChannelRequest;
use App\Models\Channel;

class ChannelsController extends BaseController
{
    protected $userEntity;
    
    public function __construct(UserEntity $userEntity) {
        $this->userEntity = $userEntity;
    }
    
    public function store(ChannelRequest $request, Channel $channel) {
        $user = $this->userEntity->getModel();
        
        $channel->title = clean($request->title, 'user_body');
        $channel->link = clean($request->link, 'user_body');
        $channel->user_id = $user->id;
        $count = Channel::count();
        $channel->sort = $count + 1;
        $channel->save();
        $data = $channel->toArray();
        return $this->respondWithSuccess('ok', $data);
    }
    
    public function update(ChannelRequest $request, Channel $channel) {
        $channel->title = clean($request->title, 'user_body');
        $channel->link = clean($request->link, 'user_body');
        $channel->save();
        $data = $channel->toArray();
        return $this->respondWithSuccess('ok', $data);
    }
    
    public function index() {
        $page = (int)request()->input('page', 1);
        $pageSize = (int)request()->input('size', 10);
        
        $channels = Channel::forPage($page, $pageSize)->get();
        $count = Channel::count();
        $data['list'] = $channels->toArray();
        $data['total'] = $count;
        $data['current_page'] = $page;
        $data['per_page'] = $pageSize;
        return $this->respondWithSuccess('ok', $data);
    }
    
    public function show(Channel $channel) {
        $data = $channel->toArray();
        return $this->respondWithSuccess('ok', $data);
    }
    
    public function destroy(Channel $channel) {
        $check = $channel->delete();
        if($check) {
            return $this->respondWithSuccess('ok');
        } else {
            return $this->respondWithErrors('删除失败');
        }
    }
    
}
